<template>
    <div>
        <div title="轮播图">
            <van-swipe :autoplay="3000" :width="500" :height="400">
                <van-swipe-item v-for="(image, index) in images" :key="index">
                    <van-image lazy-load :src="image" fit="contain"></van-image>
                    <!--                    <img class="swipe-img" v-lazy="image"/>-->
                </van-swipe-item>
            </van-swipe>
        </div>
        <div class="menu">
            <div class="menu-left">
                <ul>
                    <li
                        class="menu-left-item"
                        v-for="(menu, idx) in categoryList"
                        :key="idx"
                        :class="{ current: idx === currentIndex }"
                        @click="onClickLeftMenus(idx)"
                        ref="menuLeftList"
                    >
                        <p class="text">{{ menu.name }}</p>
                    </li>
                </ul>
            </div>
            <div class="menu-right" ref="rightItemList">
                <ul>
                    <li class="category" v-for="(menu, idx1) in categoryList" :key="idx1">
                        <h4 class="category-title">{{ menu.name }}</h4>
                        <ul class="category-subitem">
                            <li v-for="(sub, i) in menu.sub" :key="i">
                                <router-link
                                    class="category-subitem-wrapper"
                                    :to="{ name: 'goods_list', params: { category_id: sub.id } }"
                                >
                                    <div class="category-subitem-img">
                                        <img :src="APIDomainName + sub.img" alt/>
                                    </div>
                                    <span>{{ sub.name }}</span>
                                </router-link>
                            </li>
                        </ul>
                    </li>
                    <li class="category-bottom"></li>
                </ul>
            </div>
        </div>
    </div>
</template>

<script>
import Vue from 'vue'
import {Swipe, SwipeItem, Lazyload} from 'vant'

Vue.use(Swipe)
Vue.use(SwipeItem)
Vue.use(Lazyload);

import BScroll from "better-scroll";
import {getCategory} from "@/api/goods.js"

export default {
    data() {
        return {
            categoryList: [], //左侧文字菜单名称列表
            rightCategoryTopHeight: [],
            scrollY: 0, // 记住右菜单的滚动距离
            images: [
                this.utils.fixUrl("/uploads/swipe/swipe_cloth.png"),
                this.utils.fixUrl("/uploads/swipe/swipe_digital.png"),
                this.utils.fixUrl("/uploads/swipe/swipe_book.png"),

            ],
        };
    },
    created() {
        this.getCategoryForLeftMenus();
    },
    watch: {
        categoryList() {
            // $nextTick用来在下次DOM更新循环结束之后执行延迟回调
            this.$nextTick(() => {
                this._initBScroll(); // 初始化better-scroll
                this._initRightHeight(); // 初始化右边菜单的高度
            });
        },
    },
    computed: {
        currentIndex() {
            // 当 scrollY 发生改变时，修改左菜单的激活项
            const {scrollY, rightCategoryTopHeight} = this;
            // 从右菜单中查找元素，返回元素索引
            return rightCategoryTopHeight.findIndex((top, index) => {
                if (index === rightCategoryTopHeight.length - 2) {
                    return true;
                }
                if (scrollY >= top && scrollY < rightCategoryTopHeight[index + 1]) {
                    this._initLeftScroll(index);
                    return true;
                }
            });
        },
    },
    methods: {
        // 获取左侧菜单的分类内容
        async getCategoryForLeftMenus() {
            try {
                let result = await getCategory();
                // console.log(result)
                if (result.code == 1) {
                    this.categoryList = result.data;
                } else {
                    throw result.msg;
                }
            } catch (error) {
                this.$dialog({title: "错误", message: error})
            }
        },
        // 单击左菜单中的某一项后，将右菜单切换到对应项下面
        onClickLeftMenus(index) {
            this.scrollY = this.rightCategoryTopHeight[index];
            this.rightBscroll.scrollTo(0, -this.scrollY);
        },
        // 初始化better-scroll
        _initBScroll() {
            this.leftBscroll = new BScroll(".menu-left", {
                click: true,
                mouseWheel: true,
            });
            this.rightBscroll = new BScroll(".menu-right", {
                click: true,
                mouseWheel: true,
                probeType: 3, // 实时派发 scroll 事件
            });
            this.rightBscroll.on("scroll", (pos) => {
                this.scrollY = Math.abs(pos.y);
            });
        },
        // 初始化右边菜单的高度
        _initRightHeight() {
            let itemArray = [];
            let top = 0;
            itemArray.push(top);
            let allList = this.$refs.rightItemList.getElementsByClassName("category");
            // 将 allList 转换为普通数组进行遍历，记录每个元素的高度
            Object.values(allList).forEach((li) => {
                top += li.clientHeight;
                itemArray.push(top);
            });
            this.rightCategoryTopHeight = itemArray;

            // let bottom = this.$refs.rightItemList.getElementsByClassName("category-bottom")[0];
            // bottom.style.height = this.$refs.rightItemList.clientHeight + "px";

            // console.log(this.$refs.rightItemList.clientHeight)

        },
        // 右菜单滚动时，左菜单联动
        _initLeftScroll(index) {
            let menu = this.$refs.menuLeftList;
            let el = menu[index];
            // scrollToElement(el, time, offsetX, offsetY, easing)
            this.leftBscroll.scrollToElement(el, 300, 0, -100);
        },
    },
};
</script>

<style lang="scss" scoped>
ul {
    margin: 0;
    padding: 0;
}

li {
    list-style: none;
}

.menu {
    display: flex;
    position: absolute;
    text-align: center;
    top: 200px;
    bottom: 56px;
    // width: 100%;
    margin: 0px;
    overflow: hidden;

    .menu-left {
        flex: 0 0 80px;
        width: 80px;
        background: #f3f5f7;
        font-size: 16px;

        .menu-left-item {
            height: 54px;
            width: 100%;

            .text {
                width: 100%;
                line-height: 54px;
                margin-bottom: 0;
            }
        }

        .current {
            width: 100%;
            background: #fff;

            .text {
                color: red;
                font-weight: bold;
            }
        }
    }

    .menu-right {
        flex: 1;
        background: #fff;

        .category {
            height: 100%;

            .category-title {
                text-align: left;
                font-size: 16px;
                color: #333;
                font-weight: bold;
                padding: 10px;
            }

            .category-subitem {
                padding: 7px 10px 10px;
                display: flex;
                overflow: hidden;
                flex-flow: row wrap;

                li {
                    width: 33.3%;

                    .category-subitem-wrapper {
                        .category-subitem-img {
                            width: 100%;

                            img {
                                width: 70px;
                                height: 70px;
                            }
                        }

                        span {
                            display: inline-block;
                            font-size: 14px;
                            color: #333;
                        }
                    }
                }
            }
        }
    }
}

.swipe-img {
    width: 100%;
    height: 200px;
}
</style>
